package com.example.esp8266.Equipment.Equipment_Fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.example.esp8266.Equipment.Equipment_CtrlActivity;
import com.example.esp8266.Equipment.Fragment_CallBack;
import com.example.esp8266.R;

import android.os.Handler;
import android.os.Looper;

import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class SensorALL_Fragment extends Fragment implements View.OnClickListener {

    private View root;
    private String target_device, back_info, message_detect_network;
    private Fragment_CallBack callback;
    private ScheduledExecutorService scheduler;
    private Handler handler;
    private PieChart pieChart;
    private PieChart humidityChart;
    private TextView tem_text,hum_text,co2_text,pm25_text,lux_text,MQTT_status;
    private int states = 0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        message_detect_network = callback.getMsgFromActivity("Request Message");

        // 获取传递的数据
        Bundle args = getArguments();
        if (args != null) {
            target_device = args.getString("target_device", ""); // 目标控制设备
            back_info = args.getString("back_info", ""); // 返回上一层标识
        }

        // 检查 getActivity() 是否返回的对象为非空
        if (getActivity() != null) {
            // 获取 SharedPreferences 对象
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("my_prefs", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("previous_page", back_info);
            editor.apply();
        } else {
            Log.e("Fragment", "getActivity() returned null");
            // 可以选择在这里处理 getActivity() 返回 null 的情况，例如显示错误信息或采取其他操作
        }

    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        if (context instanceof Fragment_CallBack) {
            callback = (Fragment_CallBack) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement Fragment_CallBack");
        }
    }

    @SuppressLint("SetTextI18n")
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.sensor_all_fragment, container, false);

        MQTT_status = root.findViewById(R.id.MQTT_status_Sensor);

        tem_text = root.findViewById(R.id.temperature_value);
        hum_text = root.findViewById(R.id.humidity_value);
        co2_text = root.findViewById(R.id.co2_value_text);
        pm25_text = root.findViewById(R.id.pm25_value_text);
        lux_text = root.findViewById(R.id.lux_value_text);

        pieChart = root.findViewById(R.id.pieChart);
        humidityChart = root.findViewById(R.id.HumChart);

        View btn1 = root.findViewById(R.id.sensor_xml_view3);
        btn1.setOnClickListener(this);

        configureChart();
        setChartData(26f);

        configureHumidityChart();
        setHumidityChartData(40f);

        if (message_detect_network != null && (!message_detect_network.contains("offline")) ) {
            MQTT_status = root.findViewById(R.id.MQTT_status_Sensor);
            MQTT_status.setText("(客厅-在线)");
            MQTT_status.setTextColor(Color.parseColor("#00FA9A"));
        }
        /*
        else {
            TextView MQTT_status = root.findViewById(R.id.MQTT_status_Sensor);
            MQTT_status.setText("(故障)");
            MQTT_status.setTextColor(Color.parseColor("#fc3030"));
        }
         */

        handler = new Handler(Looper.getMainLooper());

        return root;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 初始化ScheduledExecutorService
        scheduler = Executors.newScheduledThreadPool(1);

        // 定时任务：每隔3秒执行一次performPeriodicTask()
        scheduler.scheduleWithFixedDelay(() -> handler.post(this::performPeriodicTask), 0, 3, TimeUnit.SECONDS);
    }

    @Override
    public void onClick(View v) {// 处理点击事件
        if (v.getId() == R.id.sensor_xml_view3){
            states ++;
            if (states == 3) states = 0;
            if (states == 0){
                TextView states_text = root.findViewById(R.id.sensor_switch_text);
                states_text.setText("切换-卧室");

                if (message_detect_network != null && (!message_detect_network.contains("offline")) ) {
                    MQTT_status.setTextColor(Color.parseColor("#00FA9A"));
                    MQTT_status.setText("(客厅-在线)");
                }
                else {
                    MQTT_status.setText("(客厅-离线)");
                    MQTT_status.setTextColor(Color.parseColor("#F4804B"));
                }
            } else if (states == 1) {
                TextView states_text = root.findViewById(R.id.sensor_switch_text);
                states_text.setText("切换-厨房");

                if (message_detect_network != null && (!message_detect_network.contains("offline")) ) {
                    MQTT_status.setTextColor(Color.parseColor("#00FA9A"));
                    MQTT_status.setText("(卧室-在线)");
                }
                else {
                    MQTT_status.setText("(卧室-离线)");
                    MQTT_status.setTextColor(Color.parseColor("#F4804B"));
                }
            } else if (states == 2) {
                TextView states_text = root.findViewById(R.id.sensor_switch_text);
                states_text.setText("切换-客厅");

                if (message_detect_network != null && (!message_detect_network.contains("offline")) ) {
                    MQTT_status.setTextColor(Color.parseColor("#00FA9A"));
                    MQTT_status.setText("(厨房-在线)");
                }
                else {
                    MQTT_status.setText("(厨房-离线)");
                    MQTT_status.setTextColor(Color.parseColor("#F4804B"));
                }
            }
        }
    }

    // 动态切换视图
    private void replaceFragment(Fragment fragment) {
        if (getActivity() != null) {
            FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.replace(R.id.control_fragment_view, fragment);
            transaction.commit();
        }
    }

    /** 配置图表 */
    private void configureChart() {
        pieChart.setUsePercentValues(false);
        pieChart.getDescription().setEnabled(false);
        pieChart.setExtraOffsets(0, 5, 0, 5); // 调整外部间距以适应布局

        pieChart.setDragDecelerationFrictionCoef(0.95f);

        // 配置饼图为半圆
        pieChart.setDrawHoleEnabled(true);
        pieChart.setHoleColor(Color.TRANSPARENT);
        pieChart.setHoleRadius(85f); // Adjust this to make the diameter larger
        //pieChart.setTransparentCircleRadius(20f); // Adjust this accordingly

        pieChart.setTransparentCircleColor(Color.TRANSPARENT);
        pieChart.setTransparentCircleAlpha(0);

        pieChart.setMaxAngle(180f); // 设置最大角度为180°，半圆
        pieChart.setRotationAngle(180f); // 设置旋转角度，使得半圆显示在顶部
        pieChart.setRotationEnabled(false); // 禁用旋转

        pieChart.setHighlightPerTapEnabled(false);

        pieChart.setDrawEntryLabels(false); // 关闭标签文字显示
        pieChart.getLegend().setEnabled(false); // 关闭注释
    }

    // 设置数据
    private void setChartData(float temperature) {
        List<PieEntry> entries = new ArrayList<>();

        // 最大温度为50度,动态调整
        float maxTemperature = 50f;
        float remaining = maxTemperature - temperature;

        // 添加温度数据项
        entries.add(new PieEntry(temperature, ""));
        // 添加剩余数据项以填充饼图
        entries.add(new PieEntry(remaining, ""));

        PieDataSet dataSet = new PieDataSet(entries, "Temperature");

        // 设置颜色
        List<Integer> colors = new ArrayList<>();
        colors.add(Color.argb(255,255,46,47)); // 温度对应的颜色
        colors.add(Color.argb(255,241,212,212)); // 剩余部分显示为灰色
        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(0f); // 隐藏值文字
        data.setValueTextColor(Color.TRANSPARENT);

        pieChart.setData(data);

        // 清除所有的高亮
        pieChart.highlightValues(null);
        pieChart.invalidate();
    }

    /** 配置湿度图表 */
    private void configureHumidityChart() {
        humidityChart.setUsePercentValues(false);
        humidityChart.getDescription().setEnabled(false);
        humidityChart.setExtraOffsets(0, 5, 0, 5); // 调整外部间距以适应布局

        humidityChart.setDragDecelerationFrictionCoef(0.95f);

        // 配置饼图为半圆
        humidityChart.setDrawHoleEnabled(true);
        humidityChart.setHoleColor(Color.TRANSPARENT);
        humidityChart.setHoleRadius(85f); // 调整此值以调整直径
        //humidityChart.setTransparentCircleRadius(20f); // 内圈直径

        humidityChart.setTransparentCircleColor(Color.TRANSPARENT);
        humidityChart.setTransparentCircleAlpha(0);

        humidityChart.setMaxAngle(180f); // 设置最大角度为180°，半圆
        humidityChart.setRotationAngle(360f); // 设置旋转角度，使得半圆显示在顶部
        humidityChart.setRotationEnabled(false); // 禁用旋转

        humidityChart.setHighlightPerTapEnabled(false);

        humidityChart.setDrawEntryLabels(false); // 关闭标签文字显示
        humidityChart.getLegend().setEnabled(false); // 关闭图例注释
    }

    private void setHumidityChartData(float humidity) {
        List<PieEntry> entries = new ArrayList<>();

        // 假设最大湿度为100来动态调整
        float maxHumidity = 100f;
        float remaining = maxHumidity - humidity;

        // 添加湿度数据项
        entries.add(new PieEntry(humidity, ""));
        // 添加剩余数据项以填充饼图
        entries.add(new PieEntry(remaining, ""));

        PieDataSet dataSet = new PieDataSet(entries, "Humidity");

        // 设置颜色
        List<Integer> colors = new ArrayList<>();
        colors.add(Color.argb(255, 9, 107, 255)); // 湿度对应的颜色，蓝色
        colors.add(Color.argb(255, 138, 189, 237)); // 剩余部分显示为灰色
        dataSet.setColors(colors);

        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(0f); // 隐藏值文字
        data.setValueTextColor(Color.TRANSPARENT);

        humidityChart.setData(data);

        // 清除所有的高亮
        humidityChart.highlightValues(null);
        humidityChart.invalidate();
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在离开 MainFragment 时
        callback = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        // 在 Fragment 生命周期结束时执行的操作
        if (scheduler != null) {
            scheduler.shutdown();
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
        callback = null;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        callback = null;
    }

    // 定时任务
    @SuppressLint("SetTextI18n")
    private void performPeriodicTask() {
        if (message_detect_network != null && (message_detect_network.contains("offline")) ) {
            tem_text.setText("null-℃");
            setChartData(0f);
            hum_text.setText("null-%");
            setHumidityChartData(0.0f);
            co2_text.setText("null-Ppm");
            pm25_text.setText("null-μg/m3");
            lux_text.setText("null-Lux");
            return;
        }
        if (states == 0) {
            sendMessageToActivity("ALL.001");
        } else if (states == 1) {
            sendMessageToActivity("ALL.010");
        } else if (states == 2) {
            sendMessageToActivity("ALL.100");
        }
        Equipment_CtrlActivity activity = (Equipment_CtrlActivity) getActivity();
        if(activity != null) {
            // 调用Activity的方法来切换视图
            double temperature = activity.get_sensor_value("Tem");
            double humidity = activity.get_sensor_value("Hum");
            int co2Concentration = (int) activity.get_sensor_value("Co2");
            int pmIndex = (int) activity.get_sensor_value("Pm2");
            double lightIntensity = activity.get_sensor_value("Lux");
            if (temperature == 0.0){
                return;
            }
            tem_text.setText(temperature+"℃");
            setChartData((float) temperature);
            hum_text.setText(humidity + "%");
            setHumidityChartData((float) humidity);
            co2_text.setText(co2Concentration+"Ppm");
            pm25_text.setText(pmIndex+"μg/m3");
            lux_text.setText(lightIntensity+"Lux");
        }

    }

    // 调用 callback 方法
    // 向 Activity 发数据
    private void sendMessageToActivity(String msg) {
        if (callback != null) {
            callback.sendMsgToActivity(msg);
        }
    }
}